﻿using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

using Telerik.Web.UI;
using Aspose.Excel;

namespace LenderClearingHouse
{
  public partial class MasterList : EditablePage
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack) CheckedProperties.Clear();
      
      tdMoveIcon.Visible = IsEditable();
      tdMoveLink.Visible = IsEditable();
      tdClearIcon.Visible = IsEditable();
      tdClearLink.Visible = IsEditable();

      listFilter.SearchButton.Click += new ImageClickEventHandler(SearchButton_Click);
      //RadAjaxManager.AjaxSettings.AddAjaxSetting(Grid, Grid);
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        Grid.MasterTableView.EditFormSettings.EditFormType = GridEditFormType.WebUserControl;
        Grid.MasterTableView.EditFormSettings.UserControlName = "MasterListEditControl.ascx";
        Grid.UpdateCommand += new GridCommandEventHandler(grid_UpdateCommand);
        Grid.InsertCommand += new GridCommandEventHandler(grid_InsertCommand);
        Grid.AllowAutomaticInserts = false;
        Grid.AllowAutomaticUpdates = false;
    }

    void SearchButton_Click(object sender, ImageClickEventArgs e)
    {
      Grid.Rebind();
      listFilter.ClearFilter();
    }

    static List<long> CheckedProperties
    {
      get
      {
        List<long> result = HttpContext.Current.Session["CheckedProperties"] as List<long>;
        if (result == null)
        {
          result = new List<long>();
          HttpContext.Current.Session["CheckedProperties"] = result;
        }

        return result;
      }
    }

    protected override Control GetGridContainer()
    {
      return phGrid;
    }

    protected override string GetDataSourceID()
    {
      return sqlDataSource.ID;
    }

    class CheckBoxedColumn : ITemplate
    {
      string columnName;

      public CheckBoxedColumn(string columnName)
      {
        this.columnName = columnName;
      }

      public void InstantiateIn(Control container)
      {
        CheckBox cb = new CheckBox();
        cb.ID = "checkBox";
        cb.AutoPostBack = true;
        cb.DataBinding += new EventHandler(cb_DataBinding);
        cb.CheckedChanged += new EventHandler(cb_CheckedChanged);

        container.Controls.Add(cb);
      }

      void cb_CheckedChanged(object sender, EventArgs e)
      {
        CheckBox cb = (CheckBox)sender;
        GridDataItem container = (GridDataItem)cb.NamingContainer;
        long propId = (long)container.GetDataKeyValue("PropertyId");

        if (cb.Checked)
        {
          if (!MasterList.CheckedProperties.Contains(propId))
            MasterList.CheckedProperties.Add(propId);
        }
        else
        {
          MasterList.CheckedProperties.Remove(propId);
        }
      }

      void cb_DataBinding(object sender, EventArgs e)
      {
        CheckBox cb = (CheckBox)sender;
        GridDataItem container = (GridDataItem)cb.NamingContainer;
        long propId = (long)container.GetDataKeyValue("PropertyId");
        cb.Checked = CheckedProperties.Contains(propId);
      }
    }

    protected override void SetupParameters(ParameterCollection coll)
    {
        base.SetupParameters(coll);
        coll.Add(new Parameter("VO"));
        coll.Add(new Parameter("MaxBid"));
        coll.Add(new Parameter("EstVal"));
        coll.Add(new Parameter("Site"));
        coll.Add(new Parameter("OnOff"));
    }

    protected override void CreateColumns(GridColumnCollection columns)
    {
      int newIndex = 3;
      GridTemplateColumn gtc;

      if (IsEditable())
      {
          gtc = new GridTemplateColumn()
          {
              UniqueName = "Checked",
              ItemTemplate = new CheckBoxedColumn("Checked"),
              AllowFiltering = false
          };
          gtc.HeaderStyle.Width = Unit.Pixel(30);
          columns.Add(gtc);

          ++newIndex;
      }
      else
      {
          newIndex = 2;
      }

      base.CreateColumns(columns);

      GridBoundColumn col = new GridBoundColumn();
      col.DataField = "VO";
      col.HeaderText = "v/o";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 1;
      col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Add(col);

      /*gtc = new GridTemplateColumn()
      {
          UniqueName = "VO",
          HeaderText = "v/o",
          ItemTemplate = new SpanColumn("VO"),
          EditItemTemplate = new VOColumnEdit("VO"),
          ConvertEmptyStringToNull = false,
          EditFormColumnIndex = 1,
          DataField = "VO",
          SortExpression = "VO"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Add(gtc);
        */

      gtc = new GridTemplateColumn()
      {
          UniqueName = "MaxBid",
          HeaderText = "MaxBd",
          ItemTemplate = new DollarColumn("MaxBid"),
          EditItemTemplate = new CurrencyColumnEdit("MaxBid"),
          ConvertEmptyStringToNull = false,
          EditFormColumnIndex = 2,
          DataField = "MaxBid",
          SortExpression = "MaxBid"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Add(gtc);

      gtc = new GridTemplateColumn()
      {
          UniqueName = "EstVal",
          HeaderText = "EstVal",
          ItemTemplate = new DollarColumn("EstVal"),
          EditItemTemplate = new CurrencyColumnEdit("EstVal"),
          ConvertEmptyStringToNull = false,
          EditFormColumnIndex = 1,
          DataField = "EstVal",
          SortExpression = "EstVal"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Add(gtc);

      col = new GridBoundColumn();
      col.DataField = "Site";
      col.HeaderText = "Site";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 1;
      col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "OnOff";
      col.HeaderText = "On/Off";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 1;
      col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Add(col);

      Utilities.MoveColumn(columns, "AuctionDate", ref newIndex);
      Utilities.MoveColumn(columns, "Trustee", ref newIndex);
      Utilities.MoveColumn(columns, "TsNumber", ref newIndex);
      Utilities.MoveColumn(columns, "Apn", ref newIndex);
      Utilities.MoveColumn(columns, "PropertyLocation", ref newIndex);
      Utilities.MoveColumn(columns, "ZipCode", ref newIndex);
      Utilities.MoveColumn(columns, "VO", ref newIndex);
      Utilities.MoveColumn(columns, "Stories", ref newIndex);
      Utilities.MoveColumn(columns, "ConstructYear", ref newIndex);
      Utilities.MoveColumn(columns, "TotalSqft", ref newIndex);
      Utilities.MoveColumn(columns, "LotSize", ref newIndex);
      Utilities.MoveColumn(columns, "Bedrooms", ref newIndex);
      Utilities.MoveColumn(columns, "Bathrooms", ref newIndex);
      Utilities.MoveColumn(columns, "GarageSqft", ref newIndex);
      Utilities.MoveColumn(columns, "Pool", ref newIndex);
      Utilities.MoveColumn(columns, "Spa", ref newIndex);
      Utilities.MoveColumn(columns, "EstimatedBid", ref newIndex);
      Utilities.MoveColumn(columns, "TsOpeningBid", ref newIndex);
      Utilities.MoveColumn(columns, "MaxBid", ref newIndex);
      Utilities.MoveColumn(columns, "EstVal", ref newIndex);
      Utilities.MoveColumn(columns, "Nos", ref newIndex);
      Utilities.MoveColumn(columns, "Liens", ref newIndex);
      Utilities.MoveColumn(columns, "Tax", ref newIndex);
      Utilities.MoveColumn(columns, "Site", ref newIndex);
      Utilities.MoveColumn(columns, "OnOff", ref newIndex);
      Utilities.MoveColumn(columns, "MiscNotes", ref newIndex);
      Utilities.MoveColumn(columns, "AssessorDesc", ref newIndex);
      Utilities.MoveColumn(columns, "Hoa", ref newIndex);
      Utilities.MoveColumn(columns, "PrelistStatus", ref newIndex);
      Utilities.MoveColumn(columns, "PurchasePrice", ref newIndex);
      Utilities.MoveColumn(columns, "RehabCosts", ref newIndex);
      Utilities.MoveColumn(columns, "LandUse", ref newIndex);
      Utilities.MoveColumn(columns, "Phase", ref newIndex);
      Utilities.MoveColumn(columns, "ListingStatus", ref newIndex);
      Utilities.MoveColumn(columns, "Client", ref newIndex);
      Utilities.MoveColumn(columns, "CloseDate", ref newIndex);
      Utilities.MoveColumn(columns, "Source", ref newIndex);
      Utilities.MoveColumn(columns, "DateRecorded", ref newIndex);

      columns.Remove(columns.FindByDataField("EscrowCompany"));

      int index = Utilities.GetColumnIndex(columns, "MiscNotes") + 1;
      columns.Insert(index, Utilities.CreateBoundColumn("NdsCorp_SaleDate", "National Default – Sale Date Previous/Projected", true));
      columns.Insert(index, Utilities.CreateBoundColumn("PriorityPost_Status", "Priority Post – Status"));
      columns.Insert(index, Utilities.CreateBoundColumn("LPS_SalesStatus", "LPS - Sales Status"));
      columns.Insert(index, Utilities.CreateTemlateDateColumn("ReconTrust_DateOfSale", "Recon Trust – Date of Sale", 0));
    }

    protected void sqlDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
      //DataAccess da = new DataAccess();
      //CountsControl.SetCounts(
      //  da.ExecuteSQLRowCount("getMasterList_ListingStatusCount 'Postponed'"),
      //  da.ExecuteSQLRowCount("getMasterList_ListingStatusCount 'Cancelled'"),
      //  da.ExecuteSQLRowCount("getMasterList_ListingStatusCount 'Sold To Bank'"),
      //  da.ExecuteSQLRowCount("getMasterList_ListingStatusCount 'Sold To 3rd Party'"));
    }

    protected void sqlDataSource_Inserting(Object sender, SqlDataSourceCommandEventArgs e)
    {
        /*SqlParameter insertedKey = new SqlParameter("@PropertyId", SqlDbType.Int);
        insertedKey.Direction = ParameterDirection.Output;
        e.Command.Parameters.Add(insertedKey);*/
    }

    protected void sqlDataSource_Inserted(Object sender, SqlDataSourceStatusEventArgs e)
    {
        /*DbCommand command = e.Command;
        string apn = command.Parameters["@Apn"].Value.ToString();
        int propertyId = Convert.ToInt32(command.Parameters["@PropertyId"].Value);
        
        DataAccess da = new DataAccess();
        DataTable dt = da.ExecuteSQL(string.Format("{0} {1}", "getPropertyInfo", propertyId.ToString()));
        if (dt.Rows.Count == 0) return;

        string location = dt.Rows[0]["Location"].ToString();
        if (location.EndsWith(", ")) 
            location = location.Remove(location.Length - 2, 2);

        string rootDir = Server.MapPath("~/PropertiesFiles");
        EnsurePropertyDirs(Session["User"] as User, rootDir, location, apn);*/

    }
          
    public static void EnsurePropertyDirs(User usr, string rootDir, string location, string apn, bool isLookup)
    {
        if (isLookup)
        {
            string pathA = Path.Combine(rootDir, "Archives\\MasterList", location);
            string propDir = Path.Combine(rootDir, "LVREO", location);
            try
            {
                if ((!Directory.Exists(propDir)) && (Directory.Exists(pathA)))
                    Directory.Move(pathA, propDir);
            }
            catch (Exception ex)
            {
            }
        }
        
        string[] arrSubDirs = new string[] { "SDREO", "LVREO" };
        foreach (string itm in arrSubDirs)
        {
            string rootSubDir = Path.Combine(rootDir, itm, location);
            if (!Directory.Exists(rootSubDir))
            {
                Directory.CreateDirectory(rootSubDir);
                PropertyDetails2.PropertiesFilesLog(usr, rootSubDir, apn);
            }

            DataAccess da = new DataAccess();
            DataTable DocumentFolders = da.ExecuteSQL("select * from DocumentFolder");
            foreach (DataRow dr in DocumentFolders.Rows)
            {
                string folderDir = Path.Combine(rootSubDir, dr["FolderName"].ToString());
                if (!Directory.Exists(folderDir))
                {
                    Directory.CreateDirectory(folderDir);
                    PropertyDetails2.PropertiesFilesLog(usr, folderDir, apn);
                }
            }
        }
    }

    protected void lnkExportToExcel_Click(object sender, EventArgs e)
    {
      /*HideColumn("DeleteButton");
      HideColumn("EditButton");
      //HideColumn("Address");

      Grid.MasterTableView.ExportToExcel();*/

        DataView dv = new DataView();
        DataTable dt = new DataTable();
        dv = sqlDataSource.Select(DataSourceSelectArguments.Empty) as DataView;
        dt = dv.ToTable();

        Excel ex = Utilities.GetExcel();
        Worksheet ws = ex.Worksheets[0];

        int startRow = 0;
        Utilities.GridToExcel(dt, Grid, ws, true, ref startRow, 8);
        ex.Save("MasterList.xls", FileFormatType.Excel2003, SaveType.OpenInExcel, HttpContext.Current.Response);
        HttpContext.Current.Response.End();
    }

    protected void lnkExportToLegal_Click(object sender, EventArgs e)
    {
     DataView dv = new DataView();
      DataTable dt = new DataTable();
      dv = sqlDataSource.Select(DataSourceSelectArguments.Empty) as DataView;
      dt = dv.ToTable();
      
      int startRow = 1;
      Utilities.GridToExcel(dt, new string[] { "PropertyLocation", 
        "AuctionDate", "Trustee", "TsNumber", "Apn", "ZipCode", "vo", "Stories", "ConstructYear", "TotalSqft", "LotSize", "Bedrooms", "Bathrooms", "GarageSqft", "Pool", "Spa", 
        "EstimatedBid", "TsOpeningBid", "MaxBid", "EstVal", "Nos", "Liens", "Tax", "Site", "OnOff", "MiscNotes", "ReconTrust_DateOfSale", "LPS_SalesStatus", "PriorityPost_Status", "NdsCorp_SaleDate", 
        "AssessorDesc", "Hoa", "PrelistStatus", "PurchasePrice", "RehabCosts", "LandUse", "Phase", "ListingStatus", "Client", "CloseDate", "Source" }, 
        "MasterListLegal", true, ref startRow, 8);
    }

    protected void lnkRefreshGrid_Click(object sender, EventArgs e)
    {
      CheckedProperties.Clear();
      Grid.Rebind();
    }

    protected void lnlMoveToWorkingList_Click(object sender, EventArgs e)
    {
      DataAccess da = new DataAccess();
      da.ExecuteSQLNonQuery(string.Format("spCopyToWorkingList @PropertyIDList = '{0}'",
        string.Join(",", CheckedProperties.ToArray())));

      Response.Redirect("~/WorkingList.aspx");
    }

    protected override string GetPropertyDetailsColumnEditorID()
    {
      return edTextBox.ID;
    }

    protected override SqlDataSource GetSqlDataSource()
    {
      return sqlDataSource;
    }

    protected override ListFilterControl GetListFilterControl()
    {
      return listFilter;
    }

    protected void lnkClearMasterList_Click(object sender, EventArgs e)
    {
      DataAccess da = new DataAccess();
      da.ExecuteSQLNonQuery("clearMasterList");
      CheckedProperties.Clear();
      Grid.Rebind();
    }

    protected override SourcePage GetSourcePage()
    {
      return SourcePage.MasterList;
    }

    protected override bool IsEditable()
    {
      return
        (CurrentUser.UserRole == UserRole.SuperAdmin)
        || (CurrentUser.UserRole == UserRole.User
            && CurrentUser.MasterlistRole == RoleAccess.ReadWrite);
    }

    protected void Archive_Click(object sender, EventArgs e)
    {     
        DataAccess da = new DataAccess();
        
        DataTable ds = da.ExecuteSQL(string.Format("spMasterListToArchive @PropertyIDList = '{0}'",
                    string.Join(",", CheckedProperties.ToArray())));

        // clear files for all the properties that does not exists in master list
        foreach (DataRow dr in ds.Rows)
        {
            var path = Server.MapPath("~/PropertiesFiles/Archives/MasterList/");
            string propDir = Path.Combine(Server.MapPath("~/PropertiesFiles/LVREO/"), dr["Location"].ToString());

            string propDirToAdd = Path.Combine(path, dr["Location"].ToString());

            try
            {
                if (!Directory.Exists(propDirToAdd)) 
                {
                    Directory.CreateDirectory(propDirToAdd); 
                }
                //if (Directory.Exists(propDir))
                Directory.Move(propDir, propDirToAdd);
            }
            catch (Exception ex)
            {
                //throw;
            }
        }

        Response.Redirect("~/MasterList.aspx");
    }

    protected void ArchiveAll_Click(object sender, EventArgs e)
    {
        DataAccess da = new DataAccess();
        DataTable ds = da.ExecuteSQL("spMasterListToArchiveAll");

        // clear files for all the properties that does not exists in master list
        foreach (DataRow dr in ds.Rows)
        {
            var path = Server.MapPath("~/PropertiesFiles/Archives/MasterList/");
            string propDir = Path.Combine(Server.MapPath("~/PropertiesFiles/LVREO/"), dr["Location"].ToString());
            string propDirToAdd = Path.Combine(path, dr["Location"].ToString());

            try
            {
                if (!Directory.Exists(propDirToAdd))
                {
                    Directory.CreateDirectory(propDirToAdd);
                }
                Directory.Move(propDir, propDirToAdd);
            }
            catch (Exception ex)
            {
                //throw;
            }
        }

        CheckedProperties.Clear();
        Grid.Rebind();
        ScriptManager.RegisterStartupScript(this, this.GetType(), "key", string.Format("alert('{0} items archived');", ds.Rows.Count), true);
    }

    protected void grid_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        MasterListEditControl userControl = (MasterListEditControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
        DataAccess da = new DataAccess();

        SqlParameter outP = new SqlParameter("@MsgErr", SqlDbType.VarChar, 1000);
        outP.Direction = ParameterDirection.Output;
        SqlParameter outPropertyId = new SqlParameter("@PropertyId", SqlDbType.Int);
        outPropertyId.Direction = ParameterDirection.Output;
        
        da.ExecuteProcedure("insertMasterList",
            new string[]
                {
                    "@IsLookup", "@OnOff", "@Trustee", "@TsNumber", "@Apn", "@PropertyLocation", "@ZipCode", "@VO", "@HOA", "@Stories",
                    "@ConstructYear", "@TotalSQft", "@LotSize", "@Bedrooms", "@Bathrooms", "@GarageSqft", "@Pool", "@Spa", "@AuctionDate",
                    "@ListingStatus", "@EstimatedBid", "@TsOpeningBid", "@MaxBid", "@EstVal", "@Tax", "@Nos",
                    "@Liens", "@Site", "@DateRecorded", "@LandUse", "@AssessorDesc", "@Phase",
                    "@Client", "@CloseDate", "@MiscNotes", "@PrelistStatus", "@PurchasePrice", "@RehabCosts",
                    "@Source", "@ReconTrust_DateOfSale", "@LPS_SalesStatus", "@PriorityPost_Status", "@NdsCorp_SaleDate"
                },
            new object[]
                {
                    userControl.IsLookup, userControl.edOnOff.Text, userControl.edTrustee.Text, userControl.edTsNumber.Text, userControl.edAPN.Text, userControl.edPropertyLocation.Text, userControl.edZipCode.Text, userControl.edvo.Text, userControl.edHoa.Text, userControl.edStories.Text,
                    userControl.edConstructYear.Text, userControl.edTotalSqft.Text, userControl.edLotSize.Text, userControl.edBedrooms.SelectedValue, userControl.edBathrooms.Text, userControl.edGarageSqft.Text, userControl.edPool.SelectedValue, userControl.edSpa.SelectedValue, userControl.edAuctionDate.DbSelectedDate,
                    userControl.edListingStatus.SelectedValue, userControl.edEstimatedBid.DbValue, userControl.edTsOpeningBid.DbValue, userControl.edMaxBid.DbValue, userControl.edEstVal.DbValue, userControl.edTax.DbValue, userControl.edNos.Text,
                    userControl.edLiens.Text, userControl.edSite.Text, userControl.edDateRecorded.DbSelectedDate, userControl.edLandUse.Text, userControl.edAssessorDesc.Text, userControl.edPhase.SelectedValue,
                    userControl.edClient.Text, userControl.edCloseDate.DbSelectedDate, userControl.edMiscNotes.Text, userControl.edPrelistStatus.Text, userControl.edPurchasePrice.DbValue, userControl.edRehabCosts.DbValue,
                    userControl.edSource.Text, userControl.edReconTrust_DateOfSale.DbSelectedDate, userControl.edLPS_SalesStatus.Text, userControl.edPriorityPost_Status.Text, userControl.edNdsCorp_SaleDate.Text
                }, new SqlParameter[] { outP, outPropertyId });

        if (string.IsNullOrEmpty(outP.Value.ToString()))
        {
            DataTable dt = da.ExecuteSQL(string.Format("{0} {1}", "getPropertyInfo", outPropertyId.Value.ToString()));
            if (dt.Rows.Count == 0) return;

            string location = dt.Rows[0]["Location"].ToString();
            if (location.EndsWith(", "))
                location = location.Remove(location.Length - 2, 2);

            string rootDir = Server.MapPath("~/PropertiesFiles");
            EnsurePropertyDirs(Session["User"] as User, rootDir, location, userControl.edAPN.Text, userControl.IsLookup);
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Error", string.Format("alert('{0}');", outP.Value.ToString()), true);
            e.Canceled = true;
        }
    }

    protected void grid_UpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        User u = Session["User"] as User;
        GridEditableItem editedItem = e.Item as GridEditableItem;
        MasterListEditControl userControl = (MasterListEditControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

        DataAccess da = new DataAccess();

        SqlParameter outP = new SqlParameter("@MsgErr", SqlDbType.VarChar, 1000);
        outP.Direction = ParameterDirection.Output;

        da.ExecuteProcedure("updateMasterList",
            new string[]
                {
                    "@PropertyID", "@OnOff", "@Trustee", "@TsNumber", "@Apn", "@PropertyLocation", "@ZipCode", "@VO", "@HOA", "@Stories",
                    "@ConstructYear", "@TotalSQft", "@LotSize", "@Bedrooms", "@Bathrooms", "@GarageSqft", "@Pool", "@Spa", "@AuctionDate",
                    "@ListingStatus", "@EstimatedBid", "@TsOpeningBid", "@MaxBid", "@EstVal", "@Tax", "@Nos",
                    "@Liens", "@Site", "@DateRecorded", "@LandUse", "@AssessorDesc", "@Phase",
                    "@Client", "@CloseDate", "@MiscNotes", "@PrelistStatus", "@PurchasePrice", "@RehabCosts",
                    "@Source", "@ReconTrust_DateOfSale", "@LPS_SalesStatus", "@PriorityPost_Status", "@NdsCorp_SaleDate"
                },
            new object[]
                {
                    (long)editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["PropertyId"],
                    userControl.edOnOff.Text, userControl.edTrustee.Text, userControl.edTsNumber.Text, userControl.edAPN.Text, userControl.edPropertyLocation.Text, userControl.edZipCode.Text, userControl.edvo.Text, userControl.edHoa.Text, userControl.edStories.Text,
                    userControl.edConstructYear.Text, userControl.edTotalSqft.Text, userControl.edLotSize.Text, userControl.edBedrooms.SelectedValue, userControl.edBathrooms.Text, userControl.edGarageSqft.Text, userControl.edPool.SelectedValue, userControl.edSpa.SelectedValue, userControl.edAuctionDate.DbSelectedDate,
                    userControl.edListingStatus.SelectedValue, userControl.edEstimatedBid.DbValue, userControl.edTsOpeningBid.DbValue, userControl.edMaxBid.DbValue, userControl.edEstVal.DbValue, userControl.edTax.DbValue, userControl.edNos.Text,
                    userControl.edLiens.Text, userControl.edSite.Text, userControl.edDateRecorded.DbSelectedDate, userControl.edLandUse.Text, userControl.edAssessorDesc.Text, userControl.edPhase.SelectedValue,
                    userControl.edClient.Text, userControl.edCloseDate.DbSelectedDate, userControl.edMiscNotes.Text, userControl.edPrelistStatus.Text, userControl.edPurchasePrice.DbValue, userControl.edRehabCosts.DbValue,
                    userControl.edSource.Text, userControl.edReconTrust_DateOfSale.DbSelectedDate, userControl.edLPS_SalesStatus.Text, userControl.edPriorityPost_Status.Text, userControl.edNdsCorp_SaleDate.Text
                }, new SqlParameter[] { outP });

        if (string.IsNullOrEmpty(outP.Value.ToString()))
        {
            //Grid.MasterTableView.ClearEditItems();
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Error", string.Format("alert('{0}');", outP.Value.ToString()), true);
            e.Canceled = true;
        }
    }
      
  }
}